# -*- coding = utf-8 -*-
# @Time    : 2025/3/31 下午5:25
# @Author  : yqk
# @File    : 动作链-12306车票查询.py
# @Software: PyCharm

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

# 配置Chrome选项
opt = Options()
opt.add_argument("--disable-blink-features=AutomationControlled")
opt.add_experimental_option('excludeSwitches', ['enable-automation'])
opt.add_experimental_option("detach", True)

# 设置ChromeDriver路径
service = Service(r'D:\python-code\chromedriver-win64\chromedriver.exe')

# 初始化浏览器
browser = webdriver.Chrome(service=service, options=opt)
browser.implicitly_wait(5)
browser.maximize_window()

# 访问12306官网
url = "https://www.12306.cn/index/index.html"
browser.get(url)
time.sleep(3)

#把鼠标悬停在车票上
tick_element = browser.find_element(By.XPATH, '//*[@id="J-chepiao"]/a')
ActionChains(browser).move_to_element(tick_element).perform()

#点击单程进入下一个页面
one_way_element = browser.find_element(By.XPATH, '//*[@id="megamenu-3"]/div[1]/ul/li[1]/a')
ActionChains(browser).click(one_way_element).perform()

#输入出发地
time.sleep(3)
star_element = browser.find_element(By.XPATH, '//*[@id="fromStationText"]')
ActionChains(browser)\
    .click(star_element)\
    .pause(1)\
    .send_keys('成都')\
    .send_keys(Keys.ENTER)\
    .pause(1)\
    .perform()

time.sleep(2)
# 输入目的地
end_element = browser.find_element(By.XPATH, '//*[@id="toStationText"]')
ActionChains(browser)\
    .click(end_element)\
    .pause(1)\
    .send_keys('眉山')\
    .pause(1)\
    .send_keys(Keys.ENTER)\
    .perform()

#填写出发日期
date_element = browser.find_element(By.XPATH, '//*[@id="train_date"]')
ActionChains(browser)\
    .click(date_element)\
    .pause(1)\
    .send_keys(Keys.ARROW_RIGHT, Keys.ARROW_RIGHT)\
    .pause(1)\
    .send_keys(Keys.BACKSPACE, Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE,Keys.BACKSPACE)\
    .pause(1)\
    .send_keys('2025-04-03', Keys.ENTER)\
    .perform()

# 勾选高铁
train_element = browser.find_element(By.XPATH, '//*[@value="G"]').click()

# 勾选发车时间
time_element = browser.find_element(By.XPATH, '//*[@id="cc_start_time"]')
Select(time_element).select_by_visible_text('12:00--18:00')
# 点击查询
browser.find_element(By.XPATH, '//*[@id="query_ticket"]').click()
